package com.runen.infinitemovement.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.runen.infinitemovement.R;
import com.runen.infinitemovement.adapter.MyTeamAdapter;
import com.runen.infinitemovement.adapter.MyTeamPriceAdapter;
import com.runen.infinitemovement.base.BaseActivity;
import com.runen.infinitemovement.model.api.CompanyAPI;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.base.BaseResponseEntity;
import com.runen.infinitemovement.model.entity.AllTeamGroupUserEntity;
import com.runen.infinitemovement.model.entity.EventBusEntity;
import com.runen.infinitemovement.model.entity.MyLegionInfoEntity;
import com.runen.infinitemovement.model.entity.MyTeamPriceEntity;
import com.runen.infinitemovement.model.entity.PictrueEntity;
import com.runen.infinitemovement.model.enums.ActivityCompat;
import com.runen.infinitemovement.tool.CommonUtil;
import com.runen.infinitemovement.tool.GlideUtils;
import com.runen.infinitemovement.tool.UiUtil;
import com.runen.infinitemovement.widget.imageview.RoundedCornersImage;
import com.runen.infinitemovement.widget.popupwind.AddCorpsPoppupWindow;
import com.runen.infinitemovement.widget.popupwind.CommonDialog;
import com.runen.infinitemovement.widget.popupwind.HandOverTeamPoppupWindow;
import com.runen.infinitemovement.widget.popupwind.PayPopupWindow;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.PermissionUtils;
import com.runen.rxnetlibrary.utils.ToastUtils;
import com.runen.rxnetlibrary.utils.constant.PermissionConstants;
import com.runen.rxnetlibrary.utils.helper.DialogHelper;
import com.zhihu.matisse.Matisse;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Create by LiaoDuanHong
 * Create on
 */
public class ArmyGroupManagerActivity extends BaseActivity {
    @BindView(R.id.rci_header)
    RoundedCornersImage rci_header;
    @BindView(R.id.tv_team_name)
    TextView tv_team_name;
    @BindView(R.id.tv_peoples)
    TextView tv_peoples;
    @BindView(R.id.rcv_people)
    RecyclerView rcv_people;
    @BindView(R.id.tv_max_count)
    TextView tv_max_count;
    @BindView(R.id.tv_phone)
    TextView tv_phone;
    @BindView(R.id.tv_phone1)
    TextView tv_phone1;
    @BindView(R.id.tv_desc)
    TextView tv_desc;
    @BindView(R.id.rcv_price)
    RecyclerView rcv_price;
    @BindView(R.id.ll_update)
    LinearLayout ll_update;

    private MyTeamAdapter adapter;
    private MyTeamPriceAdapter priceAdapter;
    private List<MyLegionInfoEntity.DataBean.TenantListBean> listBeans = new ArrayList<>();
    private List<MyTeamPriceEntity> priceList = new ArrayList<>();
    private int REQUEST_CODE_CHOOSE = 23;
    private List<Uri> avatar = new ArrayList<>();
    private String logo;
    private String companyId;
    private String companyName;
    private HandOverTeamPoppupWindow poppupWindow;//移交军团长
    private List<AllTeamGroupUserEntity.DataBean> tenantListBeans;
    private PayPopupWindow payPopupWindow;
    private int nowPersons;//当前军团人数
    private int updatePersons;//升级人数
    private int price;//单价
    private int selectIndex = -1;//升级选择的下标

    @Override
    protected int getLayoutId() {
        return R.layout.activity_army_group_manager;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        ButterKnife.bind(this);
        initData();
    }

    @Override
    protected boolean isUseFullScreenMode() {
        return super.isUseFullScreenMode();
    }

    private void initData() {
        showDialog();
        new CompanyAPI().myLegionInfo(new BaseResultCallback<MyLegionInfoEntity>() {
            @Override
            public void onResponse(MyLegionInfoEntity response) {
                dismissDialog();
                if (response.code == 0) {
                    if (response != null && response.data != null) {
                        setView(response.data);
                        initTeamGroupAll(false);
                    }
                } else {
                    ToastUtils.showShort(response.msg);
                }
            }

            @Override
            public void onError(Throwable e, String body) {
                if (!TextUtils.isEmpty(body)) {
                    if (body.contains("Invalid access token")) {
                        UserAPI.clearLogin();
                        startActivity(new Intent(ArmyGroupManagerActivity.this, LoginActivity2.class));
                    }
                }
            }
        });
    }

    private void initTeamGroupAll(boolean isSHow) {
        if (isSHow)
            showDialog();
        Map<String, Object> params = new HashMap<>();
        params.put("nickName", "");
        params.put("topTenantId", companyId);
        new CompanyAPI().allTeamGroup(params, new BaseResultCallback<AllTeamGroupUserEntity>() {
            @Override
            public void onResponse(AllTeamGroupUserEntity response) {
                dismissDialog();
                if (response.code == 0) {
                    //设置移交军团长 popuwindow 数据
                    tenantListBeans = response.data;
                    poppupWindow = HandOverTeamPoppupWindow.getInstances(ArmyGroupManagerActivity.this, tenantListBeans, companyId);
                    if (isSHow) {
                        showTransferLegionPopup();
                    }
                }
            }
        });
    }

    private void setView(MyLegionInfoEntity.DataBean data) {
        companyId = data.topTenantId;
        companyName = data.topTenantName;
        tv_team_name.setText(data.topTenantName);

        price = data.price;
        nowPersons = data.number;

        if (!TextUtils.isEmpty(data.logo)) {
            GlideUtils.loadImage(this, data.logo, rci_header);
        }
        //升级（超过40人才显示）
//        ll_update.setVisibility(data.number >= 40 ? View.VISIBLE : View.GONE);
        ll_update.setVisibility(View.GONE);

        String text = "共%s人";
        tv_peoples.setText(String.format(text, data.number));
        String text1 = "当前军团人数上限：<font color='#F63E5A'>%s</font>人";
        tv_max_count.setText(Html.fromHtml(String.format(text1, data.limitNumber)));
        String text2 = "商务联系：<font color='#F63E5A'>135 4104 0297</font>";
        tv_phone.setText(Html.fromHtml(text2));
        tv_phone1.setText(Html.fromHtml(text2));
        String text3 = "1.平台对每个军团免费开放100人上限，当军团超过100人时平台将收取<font color='#F63E5A'>%s元/人</font>," +
                "此费用为技术服务费用，军团创建者（军团长）可根据企业人数进行升级扩充到相应的人数。\n" +
                "2. 军团头衔可移交给其他成员，军团升级后无法撤销，无法解散。";
        tv_desc.setText(Html.fromHtml(String.format(text3, data.price)));

        //我的军团列表
        listBeans.clear();
        if (data.tenantList.size() >= 4) {
            listBeans = data.tenantList.subList(0, 4);
        } else
            listBeans.addAll(data.tenantList);
        listBeans.add(new MyLegionInfoEntity.DataBean.TenantListBean());
        adapter = new MyTeamAdapter(this);
        LinearLayoutManager llm = new GridLayoutManager(this, 5);
        rcv_people.setLayoutManager(llm);
        rcv_people.setAdapter(adapter);
        adapter.addData(listBeans);
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (TextUtils.isEmpty(listBeans.get(position).tenantName)) {
                    startActivity(new Intent(ArmyGroupManagerActivity.this, InviteFriendsActivity.class));
                }
            }
        });

        //升级军团人数列表
        priceList.clear();
        priceList.add(new MyTeamPriceEntity(false, 100));
        priceList.add(new MyTeamPriceEntity(false, 200));
        priceList.add(new MyTeamPriceEntity(false, 300));
        priceList.add(new MyTeamPriceEntity(false, 500));
        priceList.add(new MyTeamPriceEntity(false, 800));
        priceList.add(new MyTeamPriceEntity(false, 0));
        priceAdapter = new MyTeamPriceAdapter(this);
        LinearLayoutManager priceLlm = new GridLayoutManager(this, 3);
        rcv_price.setLayoutManager(priceLlm);
        rcv_price.setAdapter(priceAdapter);
        priceAdapter.addData(priceList);
        priceAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                for (int i = 0; i < adapter.getData().size(); i++) {
                    ((MyTeamPriceEntity) adapter.getData().get(i)).isSelect = false;
                }
                ((MyTeamPriceEntity) adapter.getData().get(position)).isSelect = true;
                selectIndex = position;
                adapter.notifyDataSetChanged();
                if (position == 5)
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            priceAdapter.setInputFocus();
                        }
                    }, 400);
            }
        });
        priceAdapter.setOnClick(new MyTeamPriceAdapter.OnClick() {
            @Override
            public void editClick() {
                for (int i = 0; i < priceAdapter.getData().size(); i++) {
                    ((MyTeamPriceEntity) priceAdapter.getData().get(i)).isSelect = false;
                }
                ((MyTeamPriceEntity) priceAdapter.getData().get(5)).isSelect = true;
                selectIndex = 5;
                priceAdapter.notifyDataSetChanged();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        priceAdapter.setInputFocus();
                    }
                }, 400);
            }
        });
    }

    @OnClick({R.id.top_btn_left, R.id.top_tv_right, R.id.tv_team_name, R.id.rci_header, R.id.iv_yjjtz, R.id.tv_update,
            R.id.tv_phone, R.id.tv_phone1, R.id.ll_team_group})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.top_btn_left:
                finish();
                break;
            case R.id.top_tv_right:
                Intent intent = new Intent(this, InviteFriendsActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_team_name:
                showPupop();
                break;
            case R.id.rci_header:
                onPermission();
                break;
            case R.id.iv_yjjtz:
                if (tenantListBeans != null)
                    showTransferLegionPopup();
                else
                    initTeamGroupAll(true);
                break;
            case R.id.tv_update:
                if (selectIndex == -1) {
                    ToastUtils.showShort("请选择升级军团人数");
                    return;
                }
                if (selectIndex != 5) {
                    updatePersons = priceAdapter.getData().get(selectIndex).number;
                } else {
                    if (TextUtils.isEmpty(priceAdapter.getEdittext())) {
                        ToastUtils.showShort("请输入升级军团人数");
                        return;
                    }
                    updatePersons = Integer.valueOf(priceAdapter.getEdittext());
                }
                payPopupWindow = PayPopupWindow.getInstance(this, updatePersons, price, nowPersons);
                payPopupWindow.show();
                break;
            case R.id.tv_phone:
            case R.id.tv_phone1:
                Intent intent1 = new Intent();
                intent1.setAction(Intent.ACTION_DIAL);
                intent1.setData(Uri.parse("tel:" + tv_phone1.getText().toString()));
                startActivity(intent1);
                break;
            case R.id.ll_team_group:
                Intent intentTeam = new Intent(this, CheckTeamActivity.class);
                intentTeam.putExtra("companyId", companyId);
                intentTeam.putExtra("type", 1);
                intentTeam.putExtra(ActivityCompat.TeamGroup, true);
                startActivity(intentTeam);
                break;
        }
    }

    private void showTransferLegionPopup() {
        String usInfo = "确定选择 %s 为新军团长，你将自动放弃军团长身份。";
        if (poppupWindow != null) {
            poppupWindow.show();
            poppupWindow.setOnHandOverListener(new HandOverTeamPoppupWindow.OnHandOverListener() {
                @Override
                public void onHandOver(String userId, String userName) {
                    CommonDialog.getInstance(ArmyGroupManagerActivity.this, "", String.format(usInfo, userName), "取消", "确定", 0).setOnClickListener(new CommonDialog.OnClickListener() {
                        @Override
                        public void onSendListener() {

                        }

                        @Override
                        public void onDismiss() {
                            onSure(userId);
                        }
                    });
                }
            });
        }
    }

    private void onSure(String userId) {
        showDialog();
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        new CompanyAPI().transferLegion(params, new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {
                if (response.getCode() == 0) {
                    dismissDialog();
                    poppupWindow.dismiss();
                    EventBus.getDefault().post(new EventBusEntity(EventBusEntity.CODE_104));
                    finish();
                } else {
                    ToastUtils.showShort(response.getMessage());
                }

            }
        });
    }

    AddCorpsPoppupWindow addCorpsPoppupWindow;

    private void showPupop() {
        addCorpsPoppupWindow = AddCorpsPoppupWindow.getInstance(this, companyName, true);
        addCorpsPoppupWindow.setOnHozonClickListener(new AddCorpsPoppupWindow.OnHozonClickListener() {
            @Override
            public void onHozomClick(String corpsName) {
                companyName = corpsName;
                onAddCorps();
            }
        });
        addCorpsPoppupWindow.show();
    }

    /**
     * 获取拍照权限
     */
    private void requestCamera() {
        UiUtil.getImageSelectorConfig(this, REQUEST_CODE_CHOOSE);
    }

    @SuppressLint("WrongConstant")
    private void onPermission() {
        //请求动态权限
        PermissionUtils.permission(
                PermissionConstants.STORAGE,
                PermissionConstants.CAMERA,
                PermissionConstants.WRITE_EXTERNAL_STORAGE,
                PermissionConstants.ACCESS_COARSE_LOCATION)
                .rationale(new PermissionUtils.OnRationaleListener() {
                    @Override
                    public void rationale(final ShouldRequest shouldRequest) {
                        DialogHelper.showRationaleDialog(shouldRequest);
                    }
                })
                .callback(new PermissionUtils.FullCallback() {
                    @Override
                    public void onGranted(List<String> permissionsGranted) {
                        requestCamera();
                    }

                    @Override
                    public void onDenied(List<String> permissionsDeniedForever,
                                         List<String> permissionsDenied) {
                        if (!permissionsDeniedForever.isEmpty()) {
                            DialogHelper.showOpenAppSettingDialog();
                        }
                    }
                })
                .request();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            if (data != null) {
                avatar = Matisse.obtainResult(data);
                if (avatar != null && avatar.size() > 0) {
                    Log.e("OnActivityResult ", String.valueOf(avatar.get(0)));
                    GlideUtils.loadImage(ArmyGroupManagerActivity.this, avatar.get(0).toString(), rci_header);
                    File file = null;
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
                        file = CommonUtil.uriToFileApiQ(this, avatar.get(0));
                    } else {
                        file = CommonUtil.uri2File(this, avatar.get(0));
                    }
                    updateByImgUrl(file);
                }
            }
        }
    }

    private void updateByImgUrl(File imaUrl) {
        Log.e("OnActivityResult2 ", imaUrl.toString());
        TreeMap<String, String> mapType = new TreeMap<>();
        mapType.put("type", "headImg");
        TreeMap<String, File> mapFile = new TreeMap<>();
        mapFile.put("file", imaUrl);
        new UserAPI().putFile(mapType, mapFile, new BaseResultCallback<PictrueEntity>() {
            @Override
            public void onResponse(PictrueEntity response) {
                if (response.code == 0) {
                    if (response.data != null) {
                        Message message = new Message();
                        message.what = 1;
                        Bundle bundle = new Bundle();
                        bundle.putString("headImgUrl", response.data.url);
                        message.setData(bundle);
                        handler.sendMessage(message);
                    }
                }
            }
        });
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    Bundle bundle = msg.getData();
                    String headUrl = bundle.getString("headImgUrl");
                    logo = headUrl;
                    onAddCorps();
                    break;
            }
        }
    };

    private void onAddCorps() {
        showDialog();
        JSONObject object = new JSONObject();
        try {
            object.put("teamName", companyName);
            object.put("tenantId", companyId);
            object.put("logo", logo);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new CompanyAPI().updateTeam(object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {
                if (response.getCode() == 0) {
                    dismissDialog();
                    tv_team_name.setText(companyName);
                    if (addCorpsPoppupWindow != null) {
                        addCorpsPoppupWindow.dismiss();
                    }
                    EventBus.getDefault().post(new EventBusEntity(EventBusEntity.CODE_106));
                } else {
                    ToastUtils.showShort(response.getMessage());
                }
            }
        });

    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventBusEntity event) {
        switch (event.getMsg()) {
            case EventBusEntity.CODE_106:
                initData();
                break;
            default:
                break;
        }
    }
}
